package com.doubleview.hutool;

import cn.hutool.db.nosql.redis.RedisDS;
import redis.clients.jedis.Jedis;

/**
 * @author huchengchao <huchengchao@kuaishou.com>
 * Created on 2022-07-01
 */
public class RedisUtils {

    private static String scriptSource = "if (redis.call('hlen', KEYS[1]) == 0) then\n" +
            "\treturn nil;\n" +
            "end;\n" +
            "\n" +
            "local total_balance = 0; \n" +
            "local keys = redis.call('hkeys', KEYS[1]);\n" +
            "for n, key in ipairs(keys) do\n" +
            "\ttotal_balance = total_balance + tonumber(redis.call('hget', KEYS[1], key));\n" +
            "end;\n" +
            "\n" +
            "local decr_amount = tonumber(ARGV[1])\n" +
            "if (total_balance < decr_amount) then\n" +
            "\treturn -1;\n" +
            "end;\n" +
            "\n" +
            "local result = {};\n" +
            "for n, key in ipairs(keys) do\n" +
            "\tlocal balance = tonumber(redis.call('hget', KEYS[1], key));\n" +
            "\tlocal decr_balance = 0;\n" +
            "\tif(balance == 0) then\n" +
            "\t\tredis.call('hdel', KEYS[1], key)\n" +
            "\telseif(balance >= decr_amount) then\n" +
            "\t\ttable.insert(result, key)\n" +
            "\t\ttable.insert(result, decr_amount)\n" +
            "\t\ttable.insert(result, redis.call('hincrby', KEYS[1], key, -decr_amount))\n" +
            "\t\treturn result;\n" +
            "\telseif(balance < decr_amount) then\n" +
            "\t\ttable.insert(result, key)\n" +
            "\t\ttable.insert(result, balance)\n" +
            "\t\ttable.insert(result, redis.call('hincrby', KEYS[1], key, -balance))\n" +
            "\t\tredis.call('hdel', KEYS[1], key)\n" +
            "\t\tdecr_amount = decr_amount - balance;\n" +
            "\tend;\n" +
            "end;\n" +
            "return result;";

    public static void main(String[] args) {
        Jedis jedis = RedisDS.create().getJedis();
        String sha = jedis.scriptLoad(scriptSource);
        System.out.println(sha);
        Object object = jedis.evalsha(sha, 1, "111", "10");
        System.out.println(object);
    }
}
